package cn.wolfcode.luowowo.website.param;

import cn.wolfcode.luowowo.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

//@Component 这里不配置的话则需要在启动中配置Bean
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //判断当前参数是否是支持参数解析类型, 返回值为true表示支持, 执行下面resolveArgument方法
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //参数上有UserParam注解并且参数类型为UserInfo
        return methodParameter.hasParameterAnnotation(UserParam.class) && methodParameter.getParameterType() == UserInfo.class;
    }
    //解析参数, 将方法返回值注入到形式参数UserInfo userInfo中
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取请求对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //获取reids中的userInfo
        Cookie cookie = CookieUtil.getCookie(request, UserInfoKeyPrefix.USER_INFO_COOKIE_NAME);
        if(cookie != null){
            return userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN, cookie.getValue());
        }
        return null;
    }
}